//
//  FirstTableViewController.m
//  GIFShow
//
//  Created by 陈凯 on 15/6/5.
//  Copyright (c) 2015年 CK. All rights reserved.
//

#import "FirstTableViewController.h"
#import <XHRefreshControl/XHRefreshControl.h>
#import <AFNetworking/AFNetworking.h>
#import <objc/objc.h>
#import "MySettingOptions.h"
#import "FirstBaseModel.h"
#import "WEIBO_GIRLS.h"
#import "WEIBO_JOKES.h"
#import "WEIBO_PICS.h"
#import "FirstBaseModelCell.h"
#import "WEIBO_GIRLSCell.h"
#import "WEIBO_JOKESCell.h"
#import "WEIBO_PICSCell.h"
#import <MRProgress/MRProgress.h>
//#import 
@interface FirstTableViewController ()<XHRefreshControlDelegate>
@property (nonatomic, strong) NSMutableArray * sourceArray;
@property (nonatomic, strong) XHRefreshControl * myControl;
@property (nonatomic, assign) BOOL isLoadMore;
@property (nonatomic) NSInteger page;
@property (nonatomic, strong) NSString * maxTimeStamp;
@end

@implementation FirstTableViewController

-(instancetype)initWithStyle:(UITableViewStyle)style UrlStr:(NSString *)urlStr{
    self = [super initWithStyle:style];
    if (self) {
        _urlStr =[[NSString alloc]initWithString:urlStr];
    }
    return self;
}
-(NSMutableArray *)sourceArray{
    if (!_sourceArray) {
        _sourceArray = [[NSMutableArray alloc]init];
    }
    return _sourceArray;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.myControl = [[XHRefreshControl alloc]initWithScrollView:self.tableView delegate:self];
    self.isLoadMore = NO;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.page = 0;
    // Uncomment the following line to preserve selection between presentations.
    // self.clearsSelectionOnViewWillAppear = NO;
    
    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;

    [self beginPullDownRefreshing];
    [self myTheme];
    [[NSNotificationCenter defaultCenter]addObserverForName:@"ChangeTheme" object:nil queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification *note) {
        [self myTheme];
    }];
    
}
-(void)myTheme{
    NSString * file = [MySettingOptions defaultOptions].backColor;
    if(self.view.frame.size.width == 375){
        NSString * back = [NSString stringWithFormat:@"%@6",file];
        self.tableView.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:back]];
    }else{
        self.tableView.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:file]];
    }
}

-(void)getDataSource{
   [MRProgressOverlayView dismissAllOverlaysForView:self.view animated:YES ];
    MRProgressOverlayView * progressView = [MRProgressOverlayView showOverlayAddedTo:self.view title:@"加载更多" mode:MRProgressOverlayViewModeIndeterminateSmallDefault animated:YES];
    progressView.backgroundColor = [UIColor clearColor];

    static int pagesize = 20;
    NSString * timeStamp = nil;
    NSString * myUrlStr = nil;

    if (!self.isLoadMore) {
        [self.sourceArray removeAllObjects];
        [self.tableView reloadData];
        self.page = 0;
        self.maxTimeStamp = nil;
    }
    if (self.maxTimeStamp == nil) {
        myUrlStr = [NSString stringWithFormat:self.urlStr,self.page,pagesize];
    }else{
        timeStamp = [NSString stringWithFormat:@"&max_timestamp=%@",self.maxTimeStamp];
        myUrlStr = [[NSString stringWithFormat:self.urlStr,self.page,pagesize] stringByAppendingString:timeStamp];

    }

    
    AFHTTPRequestOperationManager * httpRequestManger = [AFHTTPRequestOperationManager manager];
    httpRequestManger.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];
    [httpRequestManger GET:myUrlStr parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSError * error = nil;
        if (error) {
            NSLog(@"%@",error);
            [self.myControl endLoadMoreRefresing];
            [self.myControl endPullDownRefreshing];
            return;
        }
        NSString * className = [responseObject[@"category"] uppercaseString];
        NSDictionary * allItems = responseObject[@"items"];
        for (NSDictionary * oneItem in allItems) {
            FirstBaseModel * aModel = [[NSClassFromString(className) alloc]init];
            [aModel setValuesForKeysWithDictionary:oneItem];
            [self.sourceArray addObject:aModel];
            self.maxTimeStamp = [[NSString alloc]initWithString: aModel.update_time];
        }
        [self.myControl endLoadMoreRefresing];
        [self.myControl endPullDownRefreshing];
        [self.tableView reloadData];
        [MRProgressOverlayView dismissOverlayForView:self.view animated:YES ];
        self.page++;
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"%@",error);
        [self.myControl endLoadMoreRefresing];
        [self.myControl endPullDownRefreshing];
        [MRProgressOverlayView dismissOverlayForView:self.view animated:YES ];

        
    }];
    
}
-(void)beginLoadMoreRefreshing{
    self.isLoadMore = YES;
    [self getDataSource];
}
-(void)beginPullDownRefreshing{
    self.isLoadMore = NO;
    [self getDataSource];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)setUrlStr:(NSString *)urlStr{
    if ([urlStr isEqualToString:_urlStr]) {
        return;
    }
    _urlStr = [[NSString alloc]initWithString: urlStr];
    
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
#warning Potentially incomplete method implementation.
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
#warning Incomplete method implementation.
    // Return the number of rows in the section.

    return self.sourceArray.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    FirstBaseModel * firstModel = self.sourceArray[indexPath.row];
    NSString * cellClassName = [NSString stringWithFormat:@"%@Cell",[firstModel.class description]];
    FirstBaseModelCell *cell = [tableView dequeueReusableCellWithIdentifier:cellClassName];
    if (!cell) {
        cell = [FirstBaseModelCell cellForModel:firstModel];
    }

    cell.baseModel = firstModel;
    // Configure the cell...
    
    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    FirstBaseModel * firstModel = self.sourceArray[indexPath.row];
    UILabel * label = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, (self.view.frame.size.width-10)*0.9, 110)];
    label.numberOfLines = 0;
    label.text = firstModel.wbody;
    [label sizeToFit];
    
    CGFloat height = 0;
    if (firstModel.wpic_large) {
        height = (self.view.frame.size.width-10)*0.9 / firstModel.wpic_m_width.floatValue * firstModel.wpic_m_height.floatValue;
    }
    

    return height + label.frame.size.height + self.view.frame.size.width*0.15 +self.view.frame.size.width*0.12;
}
/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
